# -*- coding: utf-8 -*-

import numpy as np
import pandas as pd
import string


def pd_MultiIndex():
    # MultiIndex,tuple
    # 多重索引的元素是元组
    # 类似表格中的合并单元格

    tuple_list = [('x', 'y'), ('x', 'z'), ('y', 'z')]

    mi = pd.MultiIndex.from_tuples(tuples=tuple_list, names=['I', 'II'])
    print(mi)
    n = 5

    # 多重索引
    df1 = pd.DataFrame(np.arange(mi.size * n).reshape(mi.size, n),
                       index=mi, columns=list(string.ascii_uppercase[:n]))
    print('df:----------\n', df1, sep='')

    # 多级别列
    df2 = pd.DataFrame(np.arange(n * mi.size).reshape(n, mi.size),
                       index=list(string.ascii_lowercase[:n]), columns=mi)
    print('df:----------\n', df2, sep='')

    pass


def pd_DatatimeIndex():
    n = 26

    """
    时间序列DatatimeIndex
        开始start
        结束end
        时期periods
        频率freq
    """
    date_column = 'date_column'
    di = pd.date_range(start='2020-01-01', periods=n, freq='W', name=date_column)
    print(type(di))
    print(di)
    print(di[1])
    print(type(di[1]))

    df = pd.DataFrame(data=np.arange(0, n * n, 1).reshape(n, n),
                      index=di,
                      columns=list(string.ascii_uppercase[:n]))

    print('df:----------\n', df, sep='')

    # 重新采样：规则rule
    df1 = df.resample('3M', label='right').sum()
    print('df:----------\n', df1, sep='')

    # 前后平移

    df2 = df.shift(periods=5, freq='M')
    print('df:----------\n', df2, sep='')

    # 可实现移动窗口机制

    # 补齐数据
    date_range = pd.date_range(start='2020-01-01', end='2020-12-01', freq='D', name=date_column)
    # df.set_index(date_column)
    df = df.reindex(date_range).reset_index()
    df[date_column] = df[date_column].dt.date

    pass


def pd_PeriodIndex():
    pass


if __name__ == '__main__':

    pd_DatatimeIndex()
    pass
